var $onlineCourseTable = $('#onlineCourse');//线上课程
var $offlineCourseTable = $('#offlineCourse');//线下课程
var $valueAddedServicesTable = $('#valueAddedServices');//增值服务

var memberProductId = $('#productBs').text();//会员id
var serviceType = 1;//课程类型
var memberId;
var contactArr;//课程类型数据
var courseClassArr;//课程小类数据
var addServingCourse = 0;//新增课程分类
var addServingCourseClass = 0;//新增课程小类分类
var $addCourseTable = $('#addCourseTable');//新增课程


$(function(){
    $('table').on('load-success.bs.table', function (e,data) {
        $(e.target).find('label.lyear-checkbox').on('click', function (e) {
            e.stopPropagation();
        })
    });

    cardData();
    onlineCourseInit();//线上课程
    offlineCourseTableInit();//线下课程
    valueAddedServicesTableInit();//增值服务
    // courseSubclass('')
    $('#searchCourseSubclassSelect').selectpicker({
        noneSelectedText: '全部',
    });
    // 键盘输入时重新查询列表
    $('#followContact').keyup(debounce(contactFilter, 300));

    $('#courseContent').keyup(debounce(courseContentFliter, 300));
    // 解决table中点击行选中与checkbox冲突问题
    $('.timeInput').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',
        locale: moment.locale('zh-cn'),

    }).on('dp.hide',function (event){
        if($('#editCardMessForm').data('bootstrapValidator')!=null){
            $('#editCardMessForm').data('bootstrapValidator')
                .updateStatus('remindDate', 'NOT_VALIDATED',null)
                .validateField('remindDate');
        }

    });
    $('#editCardMessForm').bootstrapValidator({
        // excluded: [":disabled"],
        fields: {
            editCardName:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '卡片名称不能为空'
                    }
                }
            },
            editNumber:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '服务次数不能为空'
                    }
                }
            },
            editCardPrice:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '价格不能为空'
                    }
                }
            },
            starTime:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '开始时间不能为空'
                    }
                }
            },
            endTime:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '结束时间不能为空'
                    }
                }
            },
            membershipLevel:{
                validators: {
                    notEmpty: {
                        message: '会员等级不能为空'
                    }
                }
            },
            editPerformanceConversionRatio:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '业绩金额比不能为空'
                    },
                    //内容最小值验证
                    greaterThan: {
                        value : 0,
                        message : '请输入0-1的数字'
                    },

                    // //正则验证
                    // regexp: {
                    //     regexp: ' \\b(0(\\.\\d{1,2})?)|1\\b',
                    //     message: '请输入0-1的数字'
                    // },
                    //内容最大值验证
                    lessThan: {
                        value : 1,
                        message : '请输入0-1的数字'
                    },
                    stringLength:{
                        max:4,
                        message:'最大可输入两位小数'
                    }
                },


            },
            whetherIncludedAchievement:{
                validators: {
                    notEmpty: {
                        message: '是否计入会员产品业绩不能为空'
                    }
                }
            }
        }
    })
});

/**
 * 功能：延迟执行函数
 * 参数：func - 目标函数  wait - 延迟时间  immediate - 第一次是否立即执行
 * */
function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}
//防止表头与表格不对齐
$(window).resize(function () {
    $onlineCourseTable.bootstrapTable('resetView');
    $offlineCourseTable.bootstrapTable('resetView');
    $valueAddedServicesTable.bootstrapTable('resetView');
});


//获取卡详情
function cardData(){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/customerProduct/detail/info',
        dataType: "json",
        data:{
            memberProductId : memberProductId
        },
        success: (function (result) {
            if (result.code == "000000") {
                $('.cardImg').attr('src',result.data[0].memberCardImg);
                $('#newsPic').attr('src',result.data[0].memberCardImg);
                $('#numberPrice').text(result.data[0].sellingCardPrice);
                $('#number').text(result.data[0].serviceNumber);
                $('#cardName').text(result.data[0].memberCardName);
                $('#membershipLevelNumber').text(result.data[0].productMembershipLevel);
                $('#time').text(result.data[0].productPeriodValidityStart+' 至 '+result.data[0].productPeriodValidityEnd);
                $('#echoStarTime').val(result.data[0].productPeriodValidityStart);
                $('#echoEndTime').val(result.data[0].productPeriodValidityEnd);
                $('#whetherIncludedAchievement').text(result.data[0].whetherIncludedAchievement == 0?'是':'否');
                $('#performanceConversionRatio').text(result.data[0].performanceConversionRatio);
                $('#whetherRenew').val(result.data[0].whetherRenew);
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 上传图片
 * @param ele
 */
function getNewsPicUpload(ele) {
    //文件选择
    var formData = new FormData();
    //获取选择文件个数
    var files = document.getElementById("files").files;
    if (files.length == 0) {
    } else {
        var path = files[0].name;
        var suffix = path.substr(path.lastIndexOf('.'));
        var lowerSuffic = suffix.toLowerCase();
        if (lowerSuffic === '.jpg' || lowerSuffic === '.png' || lowerSuffic === '.gif') {
            //选择文件，上传选择文件
            for (let i = 0; i < files.length; i++) {
                formData.append('files', $(ele)[0].files[i]);
            }

            $.ajax({
                url: '/file/upload',
                type: 'POST',
                dataType: "json",
                contentType: false,
                data: formData,
                processData: false,
                success: (function (data) {
                    if (data.code == "000000") {
                        //进行照片回显
                        var files = [];
                        files = data.data;
                        $("#newsPic").attr('src', files[0].accessUrl);
                        $("#imageId").html(files[0].uploadId);
                    }
                }),
                error: (function (res) {
                    $.alert("失败");
                })
            });
        } else {
            $.alert('上传图片格式不正确');
        }
    }
}

//保存
function sumber(){
    var bootstrapValidator = $("#editCardMessForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    var whetherIncludedAchievement = $("input:radio[name='whetherIncludedAchievement']:checked").val();
    var whetherRenew = $("input:radio[name='whetherRenew']:checked").val();
    console.log(whetherIncludedAchievement);
    $.ajax({
        type: 'post',
        async: false,
        url: '/customerProduct/detail/updateCardPrice',
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify({
            memberProductId:memberProductId,
            sellingCardPrice:$('#editCardPrice').val(),
            memberCardName:$('#editCardName').val(),
            serviceNumber:$('#editNumber').val(),
            memberCardImg:$("#imageId").text(),
            membershipLevel:$('#membershipLevel').val(),
            productPeriodValidityStart:$('#starTime').val(),
            productPeriodValidityEnd:$('#endTime').val(),
            whetherIncludedAchievement:whetherIncludedAchievement,
            whetherRenew:whetherRenew,
            performanceConversionRatio:$('#editPerformanceConversionRatio').val()
        }),
        success: (function (result) {
            if (result.code == "000000") {
                $('#editCardMessModel').modal('hide');
                cardData()
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });

}

function editBtn(){
    $("#editCardMessForm").data('bootstrapValidator').resetForm();
    $('#editCardMessModel').modal('show');
    $('#editCardPrice').val($('#numberPrice').text());
    $('#editNumber').val($('#number').text());
    $('#editCardName').val($('#cardName').text());
    $('#membershipLevel').val($('#membershipLevelNumber').text());
    $('#starTime').val($('#echoStarTime').val());
    $('#endTime').val($('#echoEndTime').val());
    $('#editPerformanceConversionRatio').val($('#performanceConversionRatio').text());

    if($('#whetherIncludedAchievement').text() == '是'){
        $('#included_achievement').prop('checked',true)
    }else  if($('#whetherIncludedAchievement').text() == '否'){
        $('#not_included_achievement').prop('checked',true)
    }
    if($('#whetherRenew').val() == '0'){
        $('#renew').prop('checked',true);
    }else if($('#whetherRenew').val() == '1'){
        $('#no_renew').prop('checked',true);
    }
}

//线上课程表格初始化
function onlineCourseInit(){
    $onlineCourseTable.bootstrapTable('destroy');
    $onlineCourseTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProduct/detail/info',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        detailView: true,                                       // 父子表
        detailFormatter: detailFormatter,                       // 定义详情显示函数
        detailViewIcon: false,                                  // 隐藏图标列
        detailViewByClick: true,                                // 隐藏图标列
        queryParams: {
            memberProductId : memberProductId
        },//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            {title: '联系人id', field: 'contactPersonId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '课程类型', field: 'courseName',  align: 'center', valign: 'middle'},
            {title: '课程小类', field: 'subName', align: 'center', valign: 'middle'},
            {title: '服务次数', field: 'serviceCount', align: 'center', valign: 'middle'},
            {title: '操作',field:'operate',align:'center',events:operateEvents,formatter: genderOpt},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var data = [];
                if(result.data[0].courseSub != null){
                    $.each(result.data[0].courseSub,function(index){
                        if(result.data[0].courseSub[index].serviceType == '1'){
                            return data.push(result.data[0].courseSub[index])
                        }
                    })
                }
                var obj = {
                    "rows": data,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '暂无数据';
        },
    })
}



//线下课程表格初始化
function offlineCourseTableInit(){
    $offlineCourseTable.bootstrapTable('destroy');
    $offlineCourseTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProduct/detail/info',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        detailView: true,                                       // 父子表
        detailFormatter: detailFormatter,                       // 定义详情显示函数
        detailViewIcon: false,                                  // 隐藏图标列
        detailViewByClick: true,                                // 隐藏图标列
        queryParams: {
            memberProductId : memberProductId
        },//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            {title: '联系人id', field: 'contactPersonId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '课程类型', field: 'courseName',  align: 'center', valign: 'middle'},
            {title: '课程小类', field: 'subName', align: 'center', valign: 'middle'},
            {title: '服务次数', field: 'serviceCount', align: 'center', valign: 'middle'},
            {title: '操作',field:'operate',align:'center',events:operateEvents,formatter: offlineGenderOpt},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var data = [];
                if(result.data[0].courseSub != null){
                    $.each(result.data[0].courseSub,function(index){
                        if(result.data[0].courseSub[index].serviceType == '2'){
                            return data.push(result.data[0].courseSub[index])
                        }
                    })
                }
                var obj = {
                    "rows": data,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '暂无数据';
        },
    })
}

//增值服务
function valueAddedServicesTableInit(){
    $valueAddedServicesTable.bootstrapTable('destroy');
    $valueAddedServicesTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProduct/detail/info',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        detailView: true,                                       // 父子表
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        // fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        detailView: true,                                       // 父子表
        detailFormatter: detailFormatter,                       // 定义详情显示函数
        detailViewIcon: false,                                  // 隐藏图标列
        detailViewByClick: true,                                // 隐藏图标列
        queryParams: {
            memberProductId : memberProductId

        },//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            {title: '联系人id', field: 'contactPersonId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '课程类型', field: 'courseName',  align: 'center', valign: 'middle'},
            {title: '课程小类', field: 'subName', align: 'center', valign: 'middle'},
            {title: '服务次数', field: 'serviceCount', align: 'center', valign: 'middle'},
            {title: '操作',field:'operate',align:'center',events:operateEvents,formatter: valueAddGenderOpt},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var data = [];
                if(result.data[0].courseSub != null){
                    $.each(result.data[0].courseSub,function(index){
                        if(result.data[0].courseSub[index].serviceType == '3'){
                            return data.push(result.data[0].courseSub[index])
                        }
                    })
                }
                var obj = {
                    "rows": data,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '暂无数据';
        },
    })
}


/**
 * 功能：注册加载子表的事件
 * 参数：index:父表当前行的行索引  row:父表当前行的Json数据对象   $detail:当前行下面创建的新行里面的td对象
 * 说明：第三个参数尤其重要，因为生成的子表的table在装载在$detail对象里面的。bootstrap table为我们生成了$detail这个对象，然后我们只需要往它里面填充我们想要的table即可。
 * */
function detailFormatter(index, row, $detail) {
    initSubTable(index, row, $detail);
}


//初始化子表格(无线循环)
initSubTable = function (index, row, $detail) {
    var id = row.relationId;
    console.log(id);
    var cur_table = $detail.html('<table id="subformTable"><caption>列表</caption></table>').find('table');
    $(cur_table).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerMemberProductCourse/selectMemberProductCourseByRelationId',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        // pagination: true,//是否显示分页
        // showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'competitorId',
        idField: 'competitorId',
        // pageSize: 5,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5]",//可供选择的每页的行数
        queryParams:{
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            memberProductRelationId:id
        },
        columns: [
            {title: '主键', field: 'memberProductCourseId', visible: false},
            {title: '非会员id', field: 'customerProductId', visible: false},
            {title: '非会员名称', field: 'customerProductName', align: 'left', width: '60', valign: 'middle'},
            {title: '服务分类',field: 'serviceClassification',align: 'left', valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice',  align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'},
            {title: '产品会员价',field: 'productMemberPrice',align: 'left', valign: 'middle'},
            {title: '课程次数', field: 'courseCount',  align: 'left', valign: 'middle'},
            {title: '兑换方式', field: 'exchangeMethodValue', align: 'left', valign: 'middle'},
            {title: '创建时间',field: 'createTm',align: 'left', valign: 'middle'},
            {title: '操作',field:'operate',align:'right',formatter: operatingForm},
        ],
        responseHandler: function (result) {
            console.log(result);
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    // "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        //无线循环取子表，直到子表里面没有记录
        onExpandRow: function (index, row, $Subdetail) {
            initSubTable(index, row, $Subdetail);
        }
    });
};

function operatingForm(value, row, index){
    return '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="删除" data-toggle="tooltip" onclick=\'addCourseDetail("'+row.memberProductCourseId+'","1")\'>删除</a>'
}

function addCourseDetail(id){
    $.ajax({
        type: "get",
        url: "/customerMemberProductCourse/delMemberProductCourseByCourseId",
        data: {
            memberProductCourseId : id
        },
        dataType: 'json',
        success: function (data, status) {
            if (data.code == '000000') {
                $.alert({
                    title: '提示',
                    content: '删除成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $("#subformTable").bootstrapTable('refresh');
                            }
                        }
                    }
                });

            } else {
                $.alert('删除失败!');
            }
        },
        error: function () {
            $.alert('删除异常，请稍后再试!');
        }
    });
}
/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 自定义操作列内容-线上课程
 */
function genderOpt(value, row, index) {
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="修改" data-toggle="tooltip" onclick=\'modify("'+row.relationId+'","1","'+row.serviceCount+'","'+row.subName+'","'+row.courseName+'","'+row.courseTypeId+'","'+row.courseSubcategoryId+'")\'><i class="mdi mdi-grease-pencil"></i>修改</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="删除" data-toggle="tooltip" onclick=\'deleteContact("'+row.relationId+'","1")\'><i class="mdi mdi-window-close"></i>删除</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="新增课程" data-toggle="tooltip" onclick=\'addCourseBtn("'+row.relationId+'","1")\'>新增课程</a>',
    ].join('');
}

/**
 * 自定义操作列内容-线下课程
 */
function offlineGenderOpt(value, row, index) {
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="修改" data-toggle="tooltip" onclick=\'modify("'+row.relationId+'","2","'+row.serviceCount+'","'+row.subName+'","'+row.courseName+'","'+row.courseTypeId+'","'+row.courseSubcategoryId+'")\'><i class="mdi mdi-grease-pencil"></i>修改</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="删除" data-toggle="tooltip" onclick=\'deleteContact("'+row.relationId+'","2")\'><i class="mdi mdi-window-close"></i>删除</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="新增课程" data-toggle="tooltip" onclick=\'addCourseBtn("'+row.relationId+'","2")\'>新增课程</a>',
    ].join('');
}
/**
 * 自定义操作列内容-增值服务
 */
function valueAddGenderOpt(value, row, index) {
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="修改" data-toggle="tooltip" onclick=\'modify("'+row.relationId+'","3","'+row.serviceCount+'","'+row.subName+'","'+row.courseName+'","'+row.courseTypeId+'","'+row.courseSubcategoryId+'")\'><i class="mdi mdi-grease-pencil"></i>修改</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="删除" data-toggle="tooltip" onclick=\'deleteContact("'+row.relationId+'","3")\'><i class="mdi mdi-window-close"></i>删除</a>',
        '<a type="button" id="sign" class="btn btn-xs btn-default m-r-5 show-btn" title="新增课程" data-toggle="tooltip" onclick=\'addCourseBtn("'+row.relationId+'","3")\'>新增课程</a>',
    ].join('');
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {


};

/**
 * --新增课程
 */
var addCourseId;

function addCourseBtn(id){
    $('#customerNameMin').val('');
    addCourseId = id;
    addCourseInitData()

}

function addCourseInitData(){
    $addCourseTable.bootstrapTable('destroy');
    $addCourseTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerMemberProductCourse/selectNotAddCustomerMemberProductCourse',//请求地址
        method: 'post',//请求方式
        contentType: "application/json;charset=utf-8",//请求内容类型
        dataType: "json",                   // 数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页
        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页

        serverSelected: true,// 开启后端分页记住已选项功能
        serverSelectedField: "customerProductId",// 已选项的唯一识别主键

        // serverSort: true,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        //
        // fixedColumns: true,     // 冻结列
        // fixedNumber: 1,         // 左侧固定列
        // fixedRightNumber: 2,    // 右侧固定列

        queryParams:queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerProductId', visible: false},
            {checkbox: true, visible: true},
            {title: '产品名称',field: 'productName',align: 'left', valign: 'middle'},
            {title: '服务分类', field: 'serviceClassification',  align: 'left',valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice',align: 'left',valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice',align: 'left',valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice',align: 'left', valign: 'middle'},
            {title: '兑换方式', field: 'exchangeMethod', visible: false},
            {title: '兑换方式', field: 'exchangeMethodValue',align: 'left',valign: 'middle'},
            {title: '创建时间', field: 'createTm', sortable: true, align: 'left', valign: 'middle'},
            {title: '服务次数',field:'serviceNumber',align:'left', formatter: serviceNumberFormat}
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                $('#newCourseModel').modal('show');
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            // $('.JCLRgrips').remove();
            // $('#customerProductTableList').css({
            //     minWidth: $('#customerProductTableList').width()
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            //     /*onResize: function () {
            //     }*/
            // });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 拼接产品列表查询条件参数
 */
function queryParams(params){
    params.productName = $('#customerNameMin').val();
    params.memberProductRelationId = addCourseId;
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;

    return JSON.stringify(params);
}

function searchMyCustomerPool(){
    addCourseInitData()
}

/**
 * --服务次数
 */
function serviceNumberFormat(){
    return ' <div>\n' +
        '            <button class="countBtn" id="additionBtn">+</button>\n' +
        '            <input type="text" value="1" class="countInp">\n' +
        '            <button class="countBtn" id="subtractionBtn">-</button>\n' +
        '        </div>'
}

$(function(){
    $(document).on("click", "#additionBtn", function(){
        let index = $(this).parent().parent().parent().index();
        $('.countInp').eq(index).val(Number($('.countInp').eq(index).val())+1)
    });
    $(document).on("click", "#subtractionBtn", function(){
        let index = $(this).parent().parent().parent().index();
        if($('.countInp').eq(index).val()>1){
            $('.countInp').eq(index).val(Number($('.countInp').eq(index).val())-1)
        }
    });
});

/**
 * --新增课程添加
 */
function addCourseSubmit(){
    // 会员产品选中数据
    var memberProductCourse = $addCourseTable.bootstrapTable("getServerSelected",true);

    if (memberProductCourse.length == 0) {
        $('#newCourseModel').modal('hide');
        return;
    }

    var memberProductCourseData = [];

    $.each(memberProductCourse,function(index,i){
        var memberProductCourseObject = {};
        memberProductCourseObject.customerProductId = i.customerProductId;
        memberProductCourseObject.serviceClassification = i.serviceClassification;
        memberProductCourseObject.productOriginalPrice = i.productOriginalPrice;
        memberProductCourseObject.productUnitPrice = i.productUnitPrice;					//产品单价
        memberProductCourseObject.productMemberPrice = i.productMemberPrice;			//产品会员价
        memberProductCourseObject.courseCount = $('.countInp').eq(index).val();				//课程次数
        memberProductCourseObject.exchangeMethod =	i.exchangeMethod;			//兑换方式
        memberProductCourseData.push(memberProductCourseObject)
    });

    $.ajax({
        type: "post",
        url: "/customerMemberProductCourse/addCustomerMemberProductCourse",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            memberProductRelationId : addCourseId,
            memberProductCourse : memberProductCourseData,
        }),
        dataType: 'json',
        success: function (data, status) {
            if (data.code == '000000') {
                $('#newCourseModel').modal('hide');
            } else {
                $.alert('请求失败!');
            }
        },
        error: function () {
            $.alert('请求失败');
        }
    });
}

/**
 * --列表删除
 */
function  deleteContact(relationId,serviceType) {
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "get",
                        url: "/customerMemberCardServing/deleteMemberCardServingById",
                        data: {
                            memberProductRelationId : relationId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                if(serviceType == '1'){
                                    onlineCourseInit();//线上课程
                                }else if(serviceType == '2'){
                                    offlineCourseTableInit();//线下课程
                                }else if(serviceType == '2'){
                                    valueAddedServicesTableInit();//增值服务
                                }
                            } else {
                                $.alert('删除失败!');
                            }
                        },
                        error: function () {
                            $.alert('删除异常，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

/**
 * --列表修改
 */
function modify(id,type,service,name,courseName,courseId,courseClassId){
    $('#staticBackdrop').modal('show');
    $('#addBtn').css('display','none');
    $('#modify').css('display','block');
    serviceType = type;
    memberId = id;
    $('#courseClassId').val(id);
    $('#courseContent').val(name == 'null'?'':name);
    $('#serviceCount').val(service);
    $('#followContact').val(courseName);
    $('#followContactId').val(courseId);
    $('#courseClassId').val(courseClassId)
}

/**
 * 课程类型、课程小类数据请求
 *
 */
function courseTypeData(params,type){
    $.ajax({
        type: 'get',
        dataType: "json",
        url: '/customerMemberCardServing/selectMemberCardServingDropDownList',
        data: params,
        success: (function (result) {
            if (result.code == "000000") {
                if(type == 1){
                    contactArr = result.data
                }else{
                    courseClassArr = result.data
                }

            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 新增弹框-课程类型
 */
function addCourse(state){
    serviceType = state;
    resetBtn();
    $('#staticBackdrop').modal('show');
    $('#addBtn').css('display','block');
    $('#modify').css('display','none');
    let obj = {parentId:state};
    courseTypeData(obj,1);
}


/**
 * 课程类型-下拉选项
 */
var foll = null;
var follTime = null;
function changeName(_this) {
    var text = $.trim($(_this).val());
    if(text != ''){
        let obj = {parentId:serviceType};
        courseTypeData(obj,1);
        let obj1 = {parentId: $('#followContactId').val()};
        courseTypeData(obj1,2);
        follTime = setTimeout(function(){
            $("#followContactList").slideDown(160);
        },500)
    }
    if (text == '' || 'null') {
        let obj = {parentId:serviceType};
        courseTypeData(obj,1);
        foll = setTimeout(function(){
            contactList(contactArr);
        },800)
    }
    if(text != ''){

    }else{
        $("#followContactList").slideDown(160);
    }

    // 点击输入框和下拉菜单以外范围，关闭提示下拉菜单
    $(document).click(function (e) {
        var con = $(_this).parents('.pull-left');
        if (!con.is(e.target) && con.has(e.target).length === 0) {
            $("#followContactList").slideUp(100);
        }
    })
}

var set = null;
var setTime = null;
/**
 * 课程小类-下拉选项
 */
function courseClassName(_this){
    var courseClassText = $.trim($(_this).val());
    if(courseClassText != ''){
        let obj = {parentId: $('#followContactId').val()};
        courseTypeData(obj,2)
    }

    if (courseClassText == '') {
        courseClassList(courseClassArr);
    }else if(courseClassText != ''){
        set = setTimeout(function(){
            courseClassList(courseClassArr);
        },800)
    }
    if(courseClassText != ''){
        setTime = setTimeout(function(){
            $("#courseClassList").slideDown(160);
        },500)
    }else{
        $("#courseClassList").slideDown(160);
    }

    // 点击输入框和下拉菜单以外范围，关闭提示下拉菜单
    $(document).click(function (e) {
        var con = $(_this).parents('.pull-left');
        if (!con.is(e.target) && con.has(e.target).length === 0) {
            $("#courseClassList").slideUp(100);
        }
    })
}

/**
 * 课程类型-下拉项渲染
 */
function contactList(data) {
    console.log(data);
    if (data.length == 0) {
        $("#followContactList").html('<li><a href="javascript:void(0);">无此课程类型，可添直接加为新课程类型</a></li>');
        addServingCourse = 1;
        console.log('添加a')
    } else {
        var html = '';
        for (var i = 0; i < data.length; i++) {
            html += '<li><a href="javascript:void(0);" class="name-item" onclick="getTel(\'' + data[i].name + '\',\'' + data[i].contactInformation + '\',\'' + data[i].id + '\')">' + data[i].name + '</a></li>';
        }
        $("#followContactList").html(html);
        clearInterval(set);
        clearInterval(setTime);
    }
}

/**
 * 课程小类-下拉项渲染
 */
function courseClassList(data) {
    if (data.length == 0) {
        $("#courseClassList").html('<li><a href="javascript:void(0);">无此课程小类，可添直接加为新课程小类</a></li>');
        console.log('添加');
        addServingCourseClass = 1
    } else {
        var html = '';
        for (var i = 0; i < data.length; i++) {
            html += '<li><a href="javascript:void(0);" class="name-item" onclick="getCourseMess(\'' + data[i].name + '\',\'' + data[i].contactInformation + '\',\'' + data[i].id + '\')">' + data[i].name + '</a></li>';
        }
        $("#courseClassList").html(html);
        clearInterval(foll);
        clearInterval(follTime);
    }
}

/**
 * 课程类型-输入框赋值
 */
function getTel(name, phone, id) {
    $('#courseContent').val('');
    $("#followContact").val(name);
    $("#followContactId").val(id);
    $("#followContactList").slideUp(100);
    let obj = {parentId:id};
    courseTypeData(obj,2)
}

/**
 * 课程小类-输入框赋值
 */
function getCourseMess(name, phone, id){
    $("#courseContent").val(name);
    $("#courseClassId").val(id);
    $("#courseClassList").slideUp(100);
}

//输入查询
function contactFilter(e) {
    $('#courseContent').val('');
    var text = $.trim($(this).val());
    var filterContactArr = [];
    for (var i = 0; i < contactArr.length; i++) {
        if (contactArr[i].name.indexOf(text) != -1) {
            filterContactArr.push(contactArr[i]);
            console.log('查到了');
            addServingCourse = 0;
            console.log(addServingCourse)
        }
    }
    console.log(e);
    contactList(filterContactArr);
}
function courseContentFliter(e){
    var text = $.trim($(this).val());
    var courseContactArr = [];
    for (var i = 0; i < courseClassArr.length; i++) {
        if (courseClassArr[i].name.indexOf(text) != -1) {
            courseContactArr.push(courseClassArr[i]);
            addServingCourseClass = 0
        }
    }
    courseClassList(courseContactArr);
}

//新增选项
function currentTarget(){
    let object;
    if(addServingCourse == 1){
        object = {
            parentId:serviceType,//父id,
            name:$('#followContact').val()//服务名称
        };
        $.ajax({
            type: 'post',
            dataType: "json",
            async: false,
            url: '/customerMemberCardServing/addServingDetail',
            contentType:'application/json;charset=UTF-8',
            data:JSON.stringify(object),
            success: (function (result) {
                if (result.code == "000000") {
                    $('#followContactId').val(result.data)
                }
            }),
            error: (function (res) {
                alert("请求失败");
            })
        });
    }

}

function addServiceItem(){
    console.log($('#followContactId').val());
    $.ajax({
        type: 'post',
        dataType: "json",
        async: false,
        url: '/customerMemberCardServing/addServingDetail',
        contentType:'application/json;charset=UTF-8',
        data:JSON.stringify({
            parentId:$('#followContactId').val(),//父id,
            name:$('#courseContent').val()//服务名称
        }),
        success: (function (result) {
            if (result.code == "000000") {
                console.log(result.data);
                $('#courseClassId').val(result.data)
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

//新增按钮
function addBtn(btnType){
    if(  $("#followContact").val()  != ''  &&    $('#serviceCount').val() != ''){
        var params;
        if(btnType == '添加'){
            if(addServingCourse == 1){
                currentTarget();

                addServiceItem()

            }
            if( addServingCourse == 0 && addServingCourseClass == 1 ){
                addServiceItem()
            }

            params = {
                memberProductId:memberProductId,
                serviceType:serviceType,//"服务类型(1:线上课程；2:线下课程；3:增值服务)"
                courseTypeId:$("#followContactId").val(),//"课程类型id"
                courseSubcategoryId:$("#courseClassId").val(),//"课程小类id"
                serviceCount:$('#serviceCount').val(),//"服务次数"
            }


        }else  if(btnType == '修改'){
            if(addServingCourse == 1 ){
                currentTarget();
                addServiceItem()

            }
            if(addServingCourse == 0 && addServingCourseClass == 1 ){
                addServiceItem()
            }

            params = {
                memberProductId:memberProductId,
                serviceType:serviceType,//"服务类型(1:线上课程；2:线下课程；3:增值服务)"
                courseTypeId:$("#followContactId").val(),//"课程类型id"
                courseSubcategoryId:$("#courseClassId").val(),//"课程小类id"
                serviceCount:$('#serviceCount').val(),//"服务次数"
                memberProductRelationId:memberId,
            }

        }
       setTimeout(function(){
           $.ajax({
               type: 'post',
               dataType: "json",
               url: '/customerMemberCardServing/addMemberCardServing',
               contentType:'application/json;charset=UTF-8',
               async: false,
               data:JSON.stringify(params),
               success: (function (result) {
                   if (result.code == "000000") {
                       $('#staticBackdrop').modal('hide');
                       if(serviceType == '1'){
                           onlineCourseInit();//线上课程
                       }else if(serviceType == '2'){
                           offlineCourseTableInit();//线下课程
                       }else if(serviceType == '2'){
                           valueAddedServicesTableInit();//增值服务
                       }
                       resetBtn()
                   }
               }),
               error: (function (res) {
                   alert("请求失败");
               })
           });
       },800)

    }else{
        alert('课程类型或服务次数不能为空')
    }
}


//重置按钮
function resetBtn(_this){
    $('#followContactId').val('');
    $('#followContact').val('');
    $('#followContactList').html('');
    $('#courseClassId').val('');
    $('#courseContent').val('');
    $('#courseClassList').html('');
    $('#serviceCount').val('')
}

(function ($) {
    'use strict';

    //给组件增加默认参数列表
    $.extend($.fn.bootstrapTable.defaults, {
        serverSelected:false,
        serverSelectedField:"id",//做统计的主键
    });

    //给组件增加方法
    $.fn.bootstrapTable.methods.push('setServerSelected','getServerSelected');

    //调用bootstrapTable组件的构造器得到对象
    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initData = BootstrapTable.prototype.initData,
        _initBody = BootstrapTable.prototype.initBody,
        _checkAll_ = BootstrapTable.prototype.checkAll_,
        _check_ = BootstrapTable.prototype.check_;

    //重写bootstrapTable的initData方法
    BootstrapTable.prototype.initData = function () {
        _initData.apply(this, Array.prototype.slice.apply(arguments));
        if(this.options.serverSelected){
            var that = this;
            if(!that.serverSelectedDate){
                that.serverSelectedDate = {
                    "rows":[],
                    "id":[]
                }
            }
            $(that.options.data).each(function(index,row){
                if($.inArray(row[that.options.serverSelectedField],that.serverSelectedDate.id)>-1){
                    row[that.header.stateField] = true;
                }
            });
        }

    };

    //重写bootstrapTable的initBody方法
    BootstrapTable.prototype.initBody = function(fixedScroll){
        _initBody.apply(this, Array.prototype.slice.apply(arguments));
        if(this.options.serverSelected){
            var that = this;
            this.$selectItem.off('click').on('click', function (event) {
                event.stopImmediatePropagation();

                var $this = $(this),
                    checked = $this.prop('checked'),
                    row = that.data[$this.data('index')];

                if ($(this).is(':radio') || that.options.singleSelect) {
                    $.each(that.options.data, function (i, row) {
                        row[that.header.stateField] = false;
                    });
                }

                row[that.header.stateField] = checked;

                if(checked){
                    var idIndex = $.inArray(row[that.options.serverSelectedField], that.serverSelectedDate.id);
                    if(idIndex==-1){
                        that.serverSelectedDate.id.push(row[that.options.serverSelectedField]);
                        that.serverSelectedDate.rows.push(row);
                    }
                }else{
                    var idIndex = $.inArray(row[that.options.serverSelectedField], that.serverSelectedDate.id);
                    if(idIndex>-1){
                        that.serverSelectedDate.id.splice(idIndex,1);
                        that.serverSelectedDate.rows.splice(idIndex,1);
                    }
                }

                if (that.options.singleSelect) {
                    that.$selectItem.not(this).each(function () {
                        that.data[$(this).data('index')][that.header.stateField] = false;
                    });
                    that.$selectItem.filter(':checked').not(this).prop('checked', false);
                }

                that.updateSelected();
                that.trigger(checked ? 'check' : 'uncheck', row, $this);
            })
        }

    };
    //重写bootstrapTable的checkAll_方法
    BootstrapTable.prototype.checkAll_ = function (checked) {
        var that = this;
        var rows;
        if(this.options.serverSelected){
            if (!checked) {
                rows = that.getSelections();
                $(rows).each(function(index, row){
                    var idIndex = $.inArray(row[that.options.serverSelectedField], that.serverSelectedDate.id);
                    if(idIndex>-1){
                        that.serverSelectedDate.id.splice(idIndex,1);
                        that.serverSelectedDate.rows.splice(idIndex,1);
                    }
                })
            }
        }
        _checkAll_.apply(that, Array.prototype.slice.apply(arguments));
        if(this.options.serverSelected){
            if (checked) {
                rows = that.getSelections();
                $(rows).each(function(index, row){
                    var idIndex = $.inArray(row[that.options.serverSelectedField], that.serverSelectedDate.id);
                    if(idIndex==-1){
                        that.serverSelectedDate.id.push(row[that.options.serverSelectedField]);
                        that.serverSelectedDate.rows.push(row);
                    }
                })
            }
        }
    };

    //重写bootstrapTable的check_方法
    BootstrapTable.prototype.check_ = function (checked, index) {
        if(this.options.serverSelected){
            var idIndex = $.inArray(this.options.data[index][this.options.serverSelectedField], this.serverSelectedDate.id);
            if(checked){
                if(idIndex==-1){
                    this.serverSelectedDate.id.push(this.options.data[index][this.options.serverSelectedField]);
                    this.serverSelectedDate.rows.push(this.options.data[index]);
                }
            }else{
                if(idIndex>-1){
                    this.serverSelectedDate.id.splice(idIndex,1);
                    this.serverSelectedDate.rows.splice(idIndex,1);
                }
            }
        }

        _check_.apply(this, Array.prototype.slice.apply(arguments));
    };

    //重写bootstrapTable的checkBy_方法
    BootstrapTable.prototype.checkBy_ = function (checked, obj) {
        if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
            return;
        }

        var that = this,
            rows = [];
        $.each(this.options.data, function (index, row) {
            if (!row.hasOwnProperty(obj.field)) {
                return false;
            }
            if ($.inArray(row[obj.field], obj.values) !== -1) {
                var $el = that.$selectItem.filter(':enabled')
                    .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
                row[that.header.stateField] = checked;
                if(this.options.serverSelected){
                    var idIndex = $.inArray(row[that.options.serverSelectedField], that.serverSelectedDate.id);
                    if(checked){
                        if(idIndex==-1){
                            that.serverSelectedDate.id.push(row[that.options.serverSelectedField]);
                            that.serverSelectedDate.rows.push(row);
                        }
                    }else{
                        if(idIndex>-1){
                            that.serverSelectedDate.id.splice(idIndex,1);
                            that.serverSelectedDate.rows.splice(idIndex,1);
                        }
                    }
                }
                rows.push(row);
                that.trigger(checked ? 'check' : 'uncheck', row, $el);
            }
        });
        this.updateSelected();
        this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
    };


    //后端分页，预设定已选项
    BootstrapTable.prototype.setServerSelected = function(data){
        if(this.options.serverSelected){
            if(data.length>0){
                if(typeof data[0] == "object"){
                    this.serverSelectedDate.rows = data;
                    var field = this.options.serverSelectedField;
                    for(var i=0;i<data.length;i++){
                        this.serverSelectedDate.id.push(this.serverSelectedDate.rows[i][field]);
                    }
                }else{
                    this.serverSelectedDate.id = data;
                }
            }
        }

    };

    //后端分页，获取已选项
    BootstrapTable.prototype.getServerSelected = function(full){
        if(this.options.serverSelected){
            if(full){
                return this.serverSelectedDate.rows
            }else{
                return this.serverSelectedDate.id
            }
        }
    };


})(jQuery);